package com.spit.fammo.network

import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.spit.fammo.api.UIHelper
import com.spit.fammo.bean.DataBean
import com.spit.fammo.util.CacheUtil
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

/**
 * 作者　: hegaojian
 * 时间　: 2022/1/13
 * 描述　: token过期拦截器
 */
class TokenOutInterceptor : Interceptor {

    val gson: Gson by lazy { Gson() }

    @kotlin.jvm.Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val response = chain.proceed(chain.request())
        return if (response.body() != null && response.body()!!.contentType() != null) {
            val mediaType = response.body()!!.contentType()
            val string = response.body()!!.string()
            val responseBody = ResponseBody.create(mediaType, string)

            try {
                val apiResponse = gson.fromJson(string, DataBean::class.java)
                if (apiResponse.Status == 204){
                    ToastUtils.showLong(apiResponse.ErrorMsg)
                    val user = CacheUtil.getUser()
                    user?.Password = null
                    CacheUtil.setUser(user)
                    CacheUtil.setToken(null)
                    UIHelper.startLoginAct()
                    ActivityUtils.finishAllActivities()
                }
            }catch (e: Exception){
                if (e.toString().contains("IllegalStateException")){

                }else{
                    ToastUtils.showLong(e.toString())
                }
            }
            response.newBuilder()
                .body(responseBody)
                .build()
        } else {
            response
        }
    }
}